package com.milo.base.cyclic;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author milogenius
 * @date 2020-04-23 15:08
 * <p>
 *     关于嵌套for循环的一个栗子
 * </p>
 */
public class DoubleForTest {

    /**缓存线程池*/
   static ExecutorService threadPool = Executors.newFixedThreadPool(10);
    @Test
    public void test1(){
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7,8,9,10,11,12);
        if (numbers != null && !numbers.isEmpty()) {
            //组次数
            int circulatCount = (int) (Math.ceil((numbers.size() / 5.0)));
            //组大小
            int circulSize = 5;
            for (int i = 0; i < circulatCount; i++) {

                final CountDownLatch countDownLatch = new CountDownLatch(circulSize);
                for (int j = i * circulSize; j < (i + 1) * circulSize; j++) {
                    final int t = j;
                    if (j < numbers.size()) {
                        threadPool.execute(new Runnable() {
                            @Override
                            public void run() {
                                System.out.println(numbers.get(t));
                            }
                        });
                        countDownLatch.countDown();
                    } else {
                        countDownLatch.countDown();
                    }
                }

            }
            // 等待本次任务中所有的线程执行完成之后，顺序关闭
            threadPool.shutdown();
            try {
                // 请求关闭，超时，线程中断等发生时都将导致阻塞，知道所有的任务都完成
                threadPool.awaitTermination(5, TimeUnit.SECONDS);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
